<template>
  <div class="deatils-container">
    <!--长图-->
    <div class="breadcrumb-img-container">
      <div class="breadcrumb-text-container">
        <div class="title">
          WEDDING RING
        </div>
        <div class="content">
          Home / Ring / Wedding ring / Wedding Ring
        </div>
        <div class="category">
          Accessories(15) | Classic(12) | Cosmetic(6) | Earings(2) | Ring(19)
        </div>
      </div>
    </div>
    <!--图片和详情-->
    <div class="details-container">
      <div class="details-content">
        <div class="left">
          <ImagesPreview
            v-if="product.srcList.length"
            :file-list="product.srcList"
            :current-index="currentIndex"
            @update:current-index="handleIndexChange"
          />
        </div>
        <div class="right">
          <div class="title">
            <h1>{{ product.name }}</h1>
          </div>
          <div class="stars">
            <el-rate v-model="rating" :colors="colors" disabled size="small" />
            <el-icon><EditPen /></el-icon>
            <span>{{ reviews.length }} Reviews</span>
          </div>
          <div class="in-stock" v-if="product.hasStock">in-stock</div>
          <div class="in-stock" v-else>out-of-stock</div>
          <div class="price">
            <span class="pre" v-if="prePrice">${{ prePrice }}</span>
            <span class="curr">${{ currPrice }}</span>
          </div>
          <div class="desc">
            {{ product.sumary }}
          </div>
          <div class="size-chart">
            <el-icon><ToiletPaper /></el-icon>
            <span>Size Chart</span>
          </div>
          <div class="add-2-cart">
            <div class="counter">
              <div class="minus" @click="handlerMinus">
                <el-icon><Minus /></el-icon>
              </div>
              <input
                type="number"
                step="1"
                min="1"
                :value="countNum"
                class="input-number"
                size="4"
                pattern="[0-9]*"
                inputmode="numeric"
              >
              <div class="plus" @click="handlerPlus">
                <el-icon><Plus /></el-icon>
              </div>
            </div>
            <button class="add" @click="onClickBuyIt">
              <el-icon><ShoppingCartFull /></el-icon>
              <span>BUY IT</span>
            </button>
          </div>
          <!-- <div class="options">
            收藏 | 对比
          </div> -->
          <div class="categories">
            <span >Categories: </span>
            <router-link
              v-for="(category, idx) in product.categories"
              :key="idx"
              class="link"
            >
              {{ category }}
            </router-link>
          </div>
          <div class="tags">
            <span>Tags: </span>
            <router-link
              v-for="(tag, idx) in product.tags"
              :key="idx"
              class="link"
            >
              {{ tag }}
            </router-link>
          </div>
          <div class="share">
            <span>share: </span>
            <div class="icon-container">
              <router-link class="icon twitter">
                <el-icon><Share /></el-icon>
              </router-link>
              <router-link class="icon facebook">
                <el-icon><Share /></el-icon>
              </router-link>
              <router-link class="icon pinterest">
                <el-icon><Share /></el-icon>
              </router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--更多信息-->
    <div class="more-infomation">
      <div class="segment-container">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <!--1-->
          <el-tab-pane label="DESCRIPTION" name="first">
            {{ product.description }}
          </el-tab-pane>
          <!--2-->
          <!-- <el-tab-pane label="ADDITIONAL INFO" name="second">
            <div class="additional-table">
              <div class="additional-line" v-for="(line, idx) in product.additionalInfoList" :key="idx">
                <div class="label">{{ line.key }}</div>
                <div class="value">{{ line.value }}</div>
              </div>
            </div>
          </el-tab-pane> -->
          <!--3-->
          <el-tab-pane :label="`REVIEWS(${reviews.length})`" name="third">
            <div class="reviews">
              <div class="reviews-left">
                <p class="summary">{{ reviews.length }} review for {{ product.name }}</p>
                <div class="one-review" v-for="(review, idx) in reviews" :key="idx">
                  <div class="avatar-cntainer">
                    <div class="avatar">
                      <!-- <img :src="review.avatar" alt="avatar"> -->
                      <el-image
                        :src="review.avatar"
                        fit="cover"
                        style="width:56px; height: 56px;"
                      >
                        <template #error>
                          <div class="image-slot">
                            <el-icon><picture-filled /></el-icon>
                          </div>
                        </template>
                      </el-image>
                    </div>
                  </div>
                  <div class="content-container">
                    <div class="review-head">
                      <div class="username">
                        <span>{{ review.nickname }}</span>
                        <span> · </span>
                        <span>{{ randomCountry(review.nickname) }}</span>
                      </div>
                      <div class="review-time">{{ formatDatetime(review.createTime) }}</div>
                      <div class="gave-stars">
                        <el-rate v-model="review.rating" :colors="colors" size="small" allow-half disabled />
                      </div>
                    </div>
                    <div class="content">{{ review.content }}</div>
                  </div>
                </div>
              </div>
              <!-- 发表评论 -->
              <!-- <div class="reviews-right">
                <p class="summary">ADD A REVIEW</p>
                <p class="summary-desc">Your email address will not be published. Required fields are marked *</p>
                <p class="property-name">Your rating *</p>
                <el-rate v-model="myReview.reviewStars" :colors="colors" allow-half />
                <p class="property-name">Your review *</p>
                <el-input v-model="myReview.review" type="textarea"/>
                <p class="property-name">Your name *</p>
                <el-input v-model="myReview.name"/>
                <p class="property-name">Your email *</p>
                <el-input v-model="myReview.email"/>
                <div class="check-box">
                  <el-checkbox v-model="myReview.saveMyInfo" />
                  <span>Save my name, email, and website in this browser for the next time I comment.</span>
                </div>
                <button class="submit-btn">SUBMIT</button>
              </div> -->
            </div>
          </el-tab-pane>
          <!--4-->
          <el-tab-pane label="SHIPPING & DELIVERY" name="fourth">
            <div class="shipping-and-delivery">
              <div class="left-img">
                <img src="@/assets/images/shipping-and-delivery/shipping-detail-1.jpg" alt="img" >
                <img src="@/assets/images/shipping-and-delivery/delivery-detail-1.jpg" alt="img" >
              </div>
              <div class="right-txt">
                <h2>AVAILABILITY AND DELIVERY</h2>
                <p>We will notify you if an article cannot be delivered for any reason. Please also note that many delivery companies and couriers do not deliver parcels on Saturdays, Sundays or holidays.</p>
                <h2>Missing orders</h2>
                <ul style="padding: 0 17px; margin: 0;">
                  <li>The costs depend on the weight of the parcel and the destination.</li>
                  <li>The exact shipping costs will be calculated at checkout.</li>
                  <li>Diam parturient dictumst parturient scelerisque nibh lectus.</li>
                </ul>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--交叉销售-->
    <div class="cross-sells">
      <div class="cross-sells-content">
        <h2>CROSS SELLS PRODUCTS</h2>
        <div class="products">
          <div class="product" v-for="(prd, idx) in crossSells" :key="idx">
            <ProductCard :product="prd" />
          </div>
        </div>
      </div>
    </div>
    <!--空白盒子-->
    <div class="instagram">
      <div class="instagram-content">
        <img v-for="(img, idx) in instagramImages" :key="idx" :src="img" alt="image">
      </div>
    </div>
    <!--弹窗-->
    <el-dialog
      v-model="dialogVisible"
      width="800"
    >
      <div class="dialog-content">
        <p>Pay Account 汇丰账户：691752141833（朱玉娟）</p>
        <a href="https://wa.me/8615879165535" target="_blank">WhatsApp ：16263426121</a>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false" size="large">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DetailPage">
import { onMounted, reactive, ref } from 'vue'
import ImagesPreview from '@/components/images/ImagesPreview.vue'
import { ToiletPaper, Minus, Plus, ShoppingCartFull, Share, PictureFilled, EditPen } from '@element-plus/icons-vue'
import ProductCard from '@/components/product-card/ProductCard.vue'

import { getProductById,getAllProducts } from '@/api/product.js'
import { getReviewsByProductId } from '@/api/review.js'
import { formatDatetime } from '@/utils/datetimeUtil.js'//1
import { randomCountry } from '@/utils/randomCountryUtil.js'//1

import { useRoute } from 'vue-router'
const route = useRoute()

const dialogVisible = ref(false)

// 评分
const rating = ref(5)
// 购物车数量
const countNum = ref(1)

// 原价
const prePrice = ref(0)
// 现价
const currPrice = ref(0)

// 产品信息
const product = reactive({
  id: -1,
  name: '',
  rating: 0,
  hasStock: true,
  sumary: '',
  categories: [],
  tags: [],
  srcList: [],
  description: '',
  additionalInfoList: []
})

const reviews = ref([])

const myReview = reactive({
  reviewStars: 0,
  review: '',
  name: '',
  email: '',
  saveMyInfo: false
})

// 当前选中图片
const currentIndex = ref(0)
// 星星颜色
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])
// 当前分段器名称
const activeName = ref('first')

// 交叉销售产品
// const crossSells = reactive([
//   {
//     id: 1,
//     imageUrl: new URL('@/assets/images/10-370x370.jpg', import.meta.url).href,
//     name: 'SLEEVE EXTERNAL',
//     price: 18000,
//     oldPrice: 25000,
//     rating:4
//   },
//   {
//     id: 3,
//     imageUrl: new URL('@/assets/images/20-370x370.jpg',import.meta.url).href,
//     name: 'SCARAB EARRING',
//     price: 18000,
//     rating:3
//   },
//   {
//     id: 2,
//     imageUrl: new URL('@/assets/images/18-370x370.jpg',import.meta.url).href,
//     name: 'BLVE ROGUE',
//     price: 18000,
//     rating:5
//   }
// ])

const crossSells = ref([])//交叉销售产品

// ins图片
const instagramImages = reactive([
  new URL('@/assets/images/instagram/ins1.jpg', import.meta.url).href,
  new URL('@/assets/images/instagram/ins2.jpg', import.meta.url).href,
  new URL('@/assets/images/instagram/ins3.jpg', import.meta.url).href,
  new URL('@/assets/images/instagram/ins4.jpg', import.meta.url).href,
  new URL('@/assets/images/instagram/ins5.jpg', import.meta.url).href
])

//随机展示推荐，洗牌算法
function shuffleArray (array) {
  const newArray = [...array];
  for( let i = newArray.length - 1; i > 0; i-- ){
    // 生成0~i的随机索引
    const randomIdx = Math.floor(Math.random() * (i + 1));
    // 交换元素（洗牌核心）
    [newArray[i], newArray[randomIdx]] = [newArray[randomIdx], newArray[i]];
  }
  return newArray;
}

// 调用接口获取产品并随机筛选4个
function getRandomProducts () {
  getAllProducts().then(res => {
    const processedProducts = res.data.map(item => ({
      id: item.id,
      name: item.name,
      imageUrl: import.meta.env.VITE_APP_BASE_FILE + (item.mainImage || ''),
      price: item.price,
      newPrice: item.newPrice
    }))
    // 洗牌后取前4个
    const shuffled = shuffleArray(processedProducts)
    crossSells.value = shuffled.slice(0, 4)
    }).catch(err => {
      console.error('获取产品数据失败:', err)
  })
}

// 切换当前图片
function handleIndexChange (newIndex) {
  currentIndex.value = newIndex;
};
// 数量-1
function handlerMinus () {
  if (countNum.value <= 1) {
    return
  }
  countNum.value--
}
// 数量+1
function handlerPlus () {
  countNum.value++
}
// 购买
function onClickBuyIt () {
  dialogVisible.value = true
}

onMounted(() => {
  // 查询产品信息
  getProductById(route.query.id).then(res => {
    // 拷贝属性
    Object.assign(product, res.data)
    // console.log(product)
    document.title = product.name
    // 原价和现价
    prePrice.value = product.newPrice ? (product.price / 100).toFixed(2) : 0
    currPrice.value = product.newPrice ? (product.newPrice / 100).toFixed(2) : (product.price / 100).toFixed(2)
    // 图集
    const imgs = product.atlas.split(',')
    const imgList = []
    for (let i = 0; i < imgs.length; i++) {
      imgList.push({
        id: i + 1,
        url: import.meta.env.VITE_APP_BASE_FILE + imgs[i]
      })
    }
    product.srcList = imgList
  })
  // 查询评论
  getReviewsByProductId(route.query.id).then(res => {
    res.data.forEach(rev => rev.avatar = import.meta.env.VITE_APP_BASE_API + rev.avatar)
    reviews.value = res.data
  })

  //查询产品推荐随机摆放四个
  getRandomProducts();
})

</script>

<style scoped lang="scss">
.deatils-container {
  width: 100%;
  // 弹窗
  .dialog-content {
    font-size: 20px;
    padding: 100px 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  // 长图
  .breadcrumb-img-container {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-image: url('@/assets/images/banner-shop.jpg');
    background-size: cover;
    background-position: 50%;
    margin-bottom: 40px;
    .breadcrumb-text-container {
      padding: 60px 0;
      width: 64%;
      color: #fff;
      .title {
        font-size: 24px;
        font-weight: 600;
        font-family: Montserrat;
      }
      .content {
        padding: 20px 0;
      }
      .category {
        display: flex;
      }
    }
  }
  // 图集和价格等
  .details-container {
    width: 100%;
    display: flex;
    justify-content: center;
    margin-bottom: 40px;
    .details-content {
      width: 62%;
      // background-color: #ccc;
      display: flex;
      justify-content: space-between;
      .left {
        width: 48%;
        // background-color: #ccc;
        padding: 0;
      }
      .right {
        width: 50%;
        background-color: #fff;
        padding: 10px 10px;
        .title {
          margin-bottom: 5px;
          h1 {
            font-weight: 600;
          }
        }
        .stars {
          margin-bottom: 5px;
          color: #666;
          span {
            margin-left: 10px;
            font-size: 14px;
          }
        }
        .in-stock {
          color: #08bb2f;
        }
        .price {
          padding: 10px 0;
          display: flex;
          align-items: flex-end;
          .pre {
            color: #888;
            font-size: 15px;
            padding: 0 8px 8px 0;
            text-decoration: line-through;
          }
          .curr {
            color: #a07936;
            font-size: 30px;
            font-weight: 600;
          }
        }
        .desc {
          color: #888;
          margin-bottom: 10px;
        }
        .size-chart {
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          span {
            margin-left: 5px;
          }
          &:hover {
            cursor: pointer;
            color: #a07936;
          }
        }
        .add-2-cart {
          display: flex;
          margin-bottom: 15px;
          .counter {
            width: 130px;
            height: 45px;
            border: 1px solid #ccc;
            display: flex;
            .minus, .plus {
              width: 40px;
              display: flex;
              align-items: center;
              justify-content: center;
              &:hover {
                cursor: pointer;
              }
            }
            .input-number {
              box-sizing: border-box;
              text-align: center;
              width: 48px;
              border: none;
            }
            .input-number::-webkit-outer-spin-button,
            .input-number::-webkit-inner-spin-button {
              -webkit-appearance: none;
              margin: 0;
            }
            .input-number:focus {
              outline: none;
              border-color: #333;
            }
          }
          .add {
            margin-left: 20px;
            padding: 0 25px;
            color: #fff;
            background-color: #a07936;
            outline: none;
            border: none;
            display: flex;
            align-items: center;
            span {
              margin-left: 8px;
            }
            &:hover {
              cursor: pointer;
              color: #000;
            }
          }
        }
        .options {
          padding: 15px 0 20px 0;
        }
        .categories, .tags {
          line-height: 30px;
          span {
            color: #222;
            font-weight: 600;
          }
          .link {
            color: #222;
            &:hover {
              color: #a07936;
            }
          }
          .link:not(:last-child)::after {
            content: ", ";
            color: #000;
            font-weight: 600;
          }
        }
        .share {
          display: flex;
          align-items: center;
          margin-top: 15px;
          span {
            color: #000;
            font-weight: 600;
          }
          .icon-container {
            display: flex;
            .icon {
              background-color: #ccc;
              padding: 8px;
              margin: 0 5px;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;
              color: #666;
              &:hover {
                color: #fff;
              }
            }
            .icon.twitter {
              &:hover {
                background-color: blue;
              }
            }
            .icon.facebook {
              &:hover {
                background-color: red;
              }
            }
            .icon.pinterest {
              &:hover {
                background-color: green;
              }
            }
          }
        }
      }
    }
  }
  // 更多信息
  .more-infomation {
    background-color: #fff;
    width: 100%;
    display: flex;
    justify-content: center;
    // 分段器
    .segment-container {
      width: 62%;
      // 成分表格
      .additional-table {
        width: 100%;
        border-left: 1px solid #ccc;
        border-top: 1px solid #ccc;
        .additional-line {
          display: flex;
          .label {
            width: 13%;
          }
          .value {
            width: 87%;
          }
          &>div {
            padding: 20px 30px;
            border-right: 1px solid #ccc;
            border-bottom: 1px solid #ccc;
          }
        }
      }
      // 评论
      .reviews {
        display: flex;
        width: 100%;
        // 左边又分为左右布局, 左边放头像, 右边放详细信息
        .reviews-left {
          // width: 55%;
          width: 100%;
          border-right: 1px solid #eee;
          padding-right: 30px;
          .summary {
            margin-bottom: 10px;
            font-size: 20px;
          }
          // 一条评论 分为 头像区域 和 内容区域
          .one-review {
            display: flex;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
            &:last-child {
              border-bottom: none;
            }
            // 头像容器
            .avatar-cntainer {
              width: 80px;
              .avatar {
                width: 56px;
                height: 56px;
                border-radius: 50%;
                border: 2px solid #ddd;
                box-sizing: content-box;
                display: flex;
                align-items: center;
                justify-content: center;
                overflow: hidden;
                img {
                  object-fit: cover;
                }
              }
            }
            // 内容容器
            .content-container {
              flex: 1;
              .review-head {
                display: flex;
                align-items: center;
                justify-content: space-between;
                .username {
                  font-size: 16px;
                  color: #777;
                  width: 60%;
                }
                .review-time {
                  font-size: 12px;
                  color: #999;
                  width: 20%;
                }
                .gave-stars {
                  width: 20%;
                  display: flex;
                  align-items: center;
                  justify-content: flex-end;
                }
              }
              .content {
                font-size: 14px;
              }
            }
          }
        }
        // 右边
        .reviews-right {
          // width: 45%;
          width: 0;
          padding-left: 30px;
          .summary {
            font-size: 20px;
          }
          .summary-desc {
            font-size: 14px;
            font-weight: 600;
            color: #777;
          }
          .property-name {
            font-size: 14px;
            font-weight: 600;
            color: #555;
            margin-top: 15px;
          }
          .el-rate {
            height: 18px;
          }
          .check-box {
            display: flex;
            align-items: flex-start;
            justify-content: center;
            padding: 10px 0;
            span {
              margin-left: 10px;
            }
          }
          .submit-btn {
            width: 100%;
            padding: 12px 0;
            border: none;
            outline: none;
            color: #fff;
            background-color: #ccc;
            transition: all 0.3s ease;
            &:hover {
              cursor: pointer;
              color: #000;
              background-color: #a07936;
            }
          }
        }
      }
      // 装运和交付
      .shipping-and-delivery {
        width: 100%;
        display: flex;
        justify-content: space-between;
        .left-img {
          width: 48%;
          margin-right: 30px;
          display: flex;
          justify-content: space-between;
          img {
            width: 49%;
            object-fit: cover;
          }
        }
        .right-txt {
          flex: 1;
          h1: {
            font-weight: 600;
          }
        }
      }
    }
  }
  // 交叉销售
  .cross-sells {
    background-color: #fff;
    width: 100%;
    display: flex;
    justify-content: center;
    .cross-sells-content {
      margin-top: 40px;
      width: 62%;
      h2 {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        font-weight: 600;
        margin-bottom: 15px;
      }
      .products {
        display: grid;
        grid-template-columns: repeat(4, 1fr); // 固定4列，等宽自适应
        grid-auto-rows: auto;
        gap: 15px;
      }
    }
  }
  // instagram
  .instagram {
    margin-top: 15px;
    background-color: #f4f4f4;
    width: 100%;
    display: flex;
    justify-content: center;
    padding: 61px 0;
    .instagram-content {
      width: 62%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      img {
        width: 20%;
      }
    }
  }
}

:deep(.el-tabs__nav-scroll) {
  height: 50px;
  border: none;
}
:deep(.el-tabs__nav-wrap:after) {
  display: none;
}
:deep(.el-tabs__nav) {
  height: 50px;
}
:deep(.el-tabs__header) {
  margin: 0;
}
:deep(.el-tabs__item) {
  font-size: 18px;
  font-weight: 600;
  color: #999;
  height: 50px;
}
:deep(.el-tabs__item.is-active) {
  color: #a07936;
}
:deep(.el-tabs__item:hover) {
  color: #a07936;
}
:deep(.el-tabs__active-bar) {
  // background-color: #a07936;
  display: none;
}
:deep(.el-tabs__content) {
  border: 1px solid #ccc;
  padding: 30px;
}

// 头像插槽默认样式
:deep(.image-slot) {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #909399;
  font-size: 30px;
}
// 输入框边框默认样式
:deep(.el-textarea__inner) {
  border-radius: 0;
}
:deep(.el-textarea__inner.is-focus) {
  box-shadow: 0 0 0 1px #000 inset;
}
:deep(.el-input__wrapper) {
  border-radius: 0;
}
:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #000 inset;
}
// 选中框
:deep(.el-checkbox__inner:hover) {
  border-color: #000;
}
</style>
